﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using MaxAlarm.Common;
using MaxAlarm.Common.Data;

namespace MaxAlarm.Data
{
    public class DataProvider
    {
        #region Singletone

        private static readonly object Locker = new object();
        private static DataProvider _instance;

        public static DataProvider Instance
        {
            get
            {
                lock (Locker)
                {
                    return _instance ?? (_instance = new DataProvider());
                }
            }
        }

        private DataProvider()
        {
            DbPath = Path.Combine(Environment.CurrentDirectory, DbName);
            ConnectionString = string.Format(Properties.DbScripts.ConnectionStringPattern, DbPath);
        }

        #endregion

        #region Events

        public event ExceptionEventHandler Error;

        public void OnError(Exception exception)
        {
            ExceptionEventHandler handler = Error;
            if (handler != null) handler(this, exception);
        }

        #endregion

        #region Properties

        private const string DbName = "MaxAlarm.db";
        private static string DbPath = string.Empty;
        private static string ConnectionString = string.Empty;

        #endregion

        #region Initialization

        public void Initialize()
        {
            try
            {
                CreateIfNotExists();
                CreateOrReplaceTables();
            }
            catch (Exception e)
            {
                OnError(e);
            }
            
        }

        private static void CreateIfNotExists()
        {
            if(File.Exists(DbPath))
                SQLiteConnection.CreateFile(DbPath);
        }

        private static void CreateOrReplaceTables()
        {
            CreateOrReplaceTable(Properties.DbScripts.AlarmsTableScript, Properties.DbScripts.AlarmsTableName);
        }

        private static void CreateOrReplaceTable(string tableName, string script)
        {
            using(var connection = new SQLiteConnection(ConnectionString).OpenAndReturn())
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = string.Format(script, tableName);
                    command.ExecuteNonQuery();
                }
            }
        }

        #endregion

        #region Read/Write

        public void WriteItems(IEnumerable<IAlarmItem> items)
        {
            try
            {

            }
            catch (Exception e)
            {
                OnError(e);
            }
        }

        public void ReadItems

        #endregion
    }
}
